package com.pogita.cleancode.testprotectionjava.controllers;

import com.pogita.cleancode.testprotectionjava.model.Book;
import com.pogita.cleancode.testprotectionjava.model.BorrowRecord;
import com.pogita.cleancode.testprotectionjava.model.Member;
import com.pogita.cleancode.testprotectionjava.model.Result;
import com.pogita.cleancode.testprotectionjava.repositories.BookRepository;
import com.pogita.cleancode.testprotectionjava.repositories.BorrowRepository;
import com.pogita.cleancode.testprotectionjava.repositories.MemberRepository;
import com.pogita.cleancode.testprotectionjava.services.PaymentService;
import com.pogita.cleancode.testprotectionjava.utils.SignUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import java.util.Optional;

@RestController
public class BorrowController {
    @Autowired
    private BookRepository bookRepository;
    @Autowired
    private MemberRepository memberRepository;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private BorrowRepository borrowRepository;

    @GetMapping("/book")
    public Result<List<Book>> findAllBook() {
        String username = getUsername();
        if (memberRepository.existsById(username)){
            return Result.ok(bookRepository.findAll());
        }
        return Result.error("非授权用户");
    }

    @GetMapping("/book/{name}")
    public Result<List<Book>> findBookByNameLike(@PathVariable String name) throws SQLException {
        String username = getUsername();
        if (memberRepository.existsById(username)){
            return Result.ok(bookRepository.findBooksByNameLike(String.format(Locale.ENGLISH, "%s%s%s", "%", name, "%")));
        }
        return Result.error("非授权用户");
    }

    @GetMapping("/book/{bookId}/borrow")
    public Result<?> borrowBook(@PathVariable Integer bookId) {
        Optional<Book> book = bookRepository.findById(bookId);
        if (!book.isPresent()) {
            return Result.error("该图书不存在");
        }

        String username = getUsername();
        Result<?> payResult = pay(username);
        if (payResult.getCode() == 0) {
            return payResult;
        }

        BorrowRecord borrowRecord = new BorrowRecord(bookId, username);
        BorrowRecord record = borrowRepository.save(borrowRecord);
        return Result.ok(record);
    }

    private Result<?> pay(String username) {
        String password = memberRepository.findById(username).orElse(new Member()).getPassword();

        long timestamp = System.currentTimeMillis();
        String sign = SignUtils.getPaySign(username, password, timestamp);

        return paymentService.pay(username, 100, sign, timestamp);
    }

    private String getUsername() {
        SecurityContext context = SecurityContextHolder.getContext();
        return context.getAuthentication().getName();
    }
}
